import os
import socket
import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import threading

import datetime
import time
import threading

try:
    # from cnocr import CnOcr
    from PIL import Image
    import cv2
    import pyperclip
    from openpyxl import load_workbook
    import pyautogui as pagui
    import tushare as tu
except Exception as e:
    print('Wx package is miss' + str(e))

#自动操作微信工具
class AutoWxGui(object):
    def __init__(self, mine = 'Afflatus'):
        # self.ocr = CnOcr()
        self.mine = mine 
        for tt in pagui.getAllTitles():
            if tt == 'WeChat' or tt == '微信':
                print('get wechat')
                self.wxwin = pagui.getWindowsWithTitle(tt)[0]
                print(self.wxwin)
        self.width, self.height = pagui.size()
        self.midwid = (self.width-self.wxwin.width)/2
        self.midhei = (self.height-self.wxwin.height)/2
        print("屏幕分辨率：",self.width, self.height)
        print("屏幕中心点:",self.midwid, self.midhei)

    # def imgToText(self, name):
    #     res = self.ocr.ocr(name)
    #     for i in res:
    #         print(i)

    # #宽55 高70
    # def divideimg(self, img):
    #     width = 55
    #     height = 70
    #     for j in range(4):
    #         for i in range(4):
    #             xy = (width*i, height*j, width*(i+1), height*(j+1))
    #             sim = img.crop(xy)
    #             sim.save(str(j*4+i) + '.jpg')
    #             self.imgToText(str(j*4+i) + '.jpg')

    # def saveScreenShot(self, location, name):
    #     im = pagui.screenshot()
    #     ov = im.crop(location)
    #     self.divideimg(ov)
    #     ov.save(name)
    #     # 将图像转换为灰度
    #     # image = cv2.imread(name)
    #     # gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    #     # gray_image = cv2.resize(gray_image, (gray_image.shape[1]*2, gray_image.shape[0]*2))
    #     # 使用阈值进行二值化处理
    #     # _, binary_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
    #     # cv2.imwrite(name, ov)
        
    # def clickImage(self, imgpath):
    #     xy = pagui.locateOnScreen(imgpath)
    #     if xy == None:
    #         pagui.alert("未找到匹配图片", "点击图片警告", "OK")
    #         return 
    #     print(pagui.center(xy))
    #     pagui.click(pagui.center(xy), duration=0.5)

    def getWxPath(self):
        if os.path.exists('wechat_path.txt'):
            with open('wechat_path.txt', 'r') as f:
                wxpath = f.read()
                print(wxpath)
        else:
            root_dir = 'C:\\'  # 从根目录开始搜索，可以根据需要更改
            wechat_paths = []
            # 遍历文件系统 路径,文件夹名字,文件名
            for root, dirs, files in os.walk(root_dir):
                # print(root, dirs, files)
                for file in files:
                    if file.lower() == 'wechat.exe':
                        wechat_paths.append(os.path.join(root, file))
            # 打印找到的微信路径
            for wechat_path in wechat_paths:
                print(wechat_path)
            wxpath = '"' + wechat_paths[0].replace('\\', '/') + '"'
            with open('wechat_path.txt', 'w', encoding='utf-8') as f:
                f.write(''.join(wxpath))
        return wxpath

    def open_wechat(self):
        # wxpath = self.getWxPath()
        # pagui.hotkey('win', 'r')
        # pagui.typewrite('cmd')
        # pagui.press('enter')
        # pagui.press('enter')
        # time.sleep(1)
        # self.typewrite(wxpath)
        # pagui.press('enter')
        # time.sleep(1)  # 等待微信应用程序打开
        # self.close_app("C:\\")
        pagui.hotkey('ctrl','alt', 'w')
        time.sleep(0.5)
        pagui.moveTo(self.wxwin.left + 10, self.wxwin.top + 10)
        time.sleep(0.5)
        pagui.dragTo(self.midwid, self.midhei,duration=0.5)
    
    def close_app(self, name):
        app = pagui.getWindowsWithTitle(name)[0]
        print('close ', app)
        pagui.click(app.left + 10, app.top + 10)
        time.sleep(0.5)
        pagui.hotkey('alt', 'f4')
        time.sleep(0.5)
        pagui.click(self.midwid+10, self.midhei+10)
        time.sleep(0.5)

    def typewrite(self, text):
        pyperclip.copy(text)
        pagui.keyDown('ctrl')
        pagui.press('v')
        pagui.keyUp('ctrl')
        # 添加适当的延迟，确保文本输入完全
        time.sleep(0.5)

    def sendclassaction(self):
        pagui.hotkey('ctrl', 'a')
        time.sleep(0.5)
        pagui.press('s')
        time.sleep(0.5)
        pagui.press('2')
        time.sleep(0.5)
        
    def sendtommoroclassaction(self):
        pagui.hotkey('ctrl', 'a')
        time.sleep(1)
        pagui.press('a')
        time.sleep(0.5)
        pagui.press('2')
        time.sleep(0.5)

    def search_chat(self, keyword):
        print('in search_chat')
        pagui.hotkey('ctrl', 'f')
        time.sleep(1)
        self.typewrite(keyword)
        pagui.press('enter')
        time.sleep(1.5)
        pagui.click(1218, 340, duration=1)
        time.sleep(0.5)
        pagui.click(920, 855, duration=1)
        self.clickImage('dianji.png')
        time.sleep(0.5)
        self.saveScreenShot((1447,115,1668,396), 'chatmember.jpg')
        # self.imgToText('chatmember.jpg')
        pagui.click(920, 855, duration=1)
        print('search_chat finished')

    def send_msg(self, msg):
        pagui.hotkey('ctrl', 'a')
        time.sleep(1)
        self.typewrite(msg)
        # pagui.press('enter')

    def msg_alarm(self, info):
        self.search_chat(self.mine)
        self.send_msg(info)
    
    def getMsgTimes(self):
        timelist = [175000, 182000, 185000, 192000, 195000, 202000, 205000, 212000, 215000, 222000]
        timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
        if timenow >= 170000:
            for index, item in enumerate(timelist):
                # print(index, item)
                if timenow >= item and timenow <= item + 5:
                    return index
        return -1
        # print(timenow)

    def readxlsx(self, path):
        global clients
        # 读取Excel文件
        workbook = load_workbook(path)
        worksheet = workbook['Sheet1']
        
        # 打印数据
        for cols in worksheet.iter_cols(values_only=True):
            coltext = []
            for col in cols:
                if type(col) is not datetime.time and col is not None:
                    coltext.append(col)
            clients.append(coltext)
        print(clients)

#微信自动摸鱼主函数
def moyuFunction(callback):
    #初始化微信自动操作类
    try:
        wx = AutoWxGui()
    except Exception as e:
        print("微信未打开," + str(e))
        pagui.alert("微信未打开" + str(e), '错误警告', 'OK')
        callback()
        return False

    #    获取群聊关键字
    wx.readxlsx('file.xlsx')
    info = 'this is a auto send message'
    timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
    global clients
    
    # wx.saveScreenShot((603,148,1061,366), 'qunliao.png')
    time.sleep(3)
    # wx.saveScreenShot((1206,324,1295,353), 'enterchat.jpg')
    # while timenow <= 223000:
    while True:
        global contact
        time.sleep(1)
        timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
        # index = wx.getMsgTimes()
        index = 1
        if index != -1:
            #输出提醒信息
            send_error = []
            wx.open_wechat()
            for client in clients[index]:
                try:
                    print(client)
                    wx.search_chat(client)
                    wx.sendclassaction()
                except Exception as e:
                    # 处理未知类型的异常
                    wx.msg_alarm("发送消息失败", e)
                    send_error.append(client)
            #发送失败错误处理
            while len(send_error) > 0:
                for msg in send_error:
                    try:
                        wx.search_chat(msg)
                        wx.send_msg(info)
                    except Exception as e:
                        # 处理未知类型的异常
                        wx.msg_alarm("重发消息失败", e)
                    else:
                        wx.msg_alarm("重发消息成功")
                        send_error.remove(msg)
        time.sleep(1)
        print("currant time:" + str(timenow))
        break
    callback()
    return True
    wx.msg_alarm("今日任务已完成, have a nice day!")

#人脸识别测试
def dataAnalysis():
    pro = tu.pro_api("df8ba8bf0035f774d5d15c760a7bdf864bd22c45887e9fc7097769f4")
    df = pro.trade_cal(exchange='SSE', is_open='1', 
                            start_date='20240708', 
                            end_date='20240711', 
                            fields='cal_date')
    print(df.head())


class myApp():
    version = '1.0.1' # app版本号
    def readfilename(self,path):     #获取ktr文件
        L=[]
        for root,dirs,files in os.walk(path):
            if root == path:
                for i in files:
                    if os.path.splitext(i)[1] == '.ktr':
                        print(i)
                        L.append(i)
        return L

    def cleanPycache(self, path):
        for root,dirs,file in os.walk(path):
            print(root)
            print(dirs)
            for dir in dirs:
                if dir == '__pycache__':
                    os.system('rm -rf ' + root + os.sep + dir)
                    print('clear finished:' + root + os.sep + dir)
            print('\n')

    def fontToCmd(self, path, location = 'E:'):
        for root,dirs,files in os.walk(path):
            for file in files:
                # print(os.path.splitext(file))
                if os.path.splitext(file)[1].lower() in ['.ttf', '.dat']:
                    print('找到字库文件:' + file)
                    input = open(file, "rb")
                    data = input.read()
                    with open('output_' + os.path.splitext(file)[0] + '.txt', 'w') as ff:
                        ff.write('~DT' + location + file + ',' + str(int(len(data))) + ',' + '\r\n')
                        i = 0
                        for byte in data:
                            i += 1
                            ff.write(str(hex(byte)[2:].zfill(2)))
                        print(str(file) + '字库数据长度：' + str(i) + '\r\n' + "转换成功" + '\r\n'+ '\r\n')
                    input.close()

    def transto1(self):
        self.stack.setCurrentIndex(0)
        self.but[0].setChecked(True)
        self.but[1].setChecked(False)
        self.but[2].setChecked(False)

    def transto2(self):
        self.stack.setCurrentIndex(1)
        self.but[0].setChecked(False)
        self.but[1].setChecked(True)
        self.but[2].setChecked(False)
    
    def transto3(self):
        self.stack.setCurrentIndex(2)
        self.but[0].setChecked(False)
        self.but[1].setChecked(False)
        self.but[2].setChecked(True)
 
    def starttransform(self):
        self.fontToCmd(path = os.getcwd(), location = self.location)

    def chooseFolder(self):
        self.folderPath = QFileDialog.getExistingDirectory(self.win, "选择文件夹")

        if self.folderPath:
            self.filelist.clear()
            files = [f for f in os.listdir(self.folderPath) if os.path.isfile(os.path.join(self.folderPath, f))]
            self.filelist.addItems(files)

    def chooseFile(self):
        file_dialog = QFileDialog()
        self.file_path, _ = file_dialog.getOpenFileName(self.win, '选择文件', '', 'All Files (*)')

        if self.file_path:
            print(f'选择的文件路径: {self.file_path}')
            with open(self.file_path, 'rb') as f:
                self.textbox.setText("")
                self.cmd = f.read()
                self.textbox.setPlaceholderText(self.file_path)
                self.fileflag = True
                print(self.cmd)

    def updatelocation(self):
        print(self.checklocation.currentIndex())
        if 0 == self.checklocation.currentIndex():
            print("RAM")
            self.location = 'R:'
        else:
            self.location = 'E:'

    def enableordisable(self, enable):
        self.connectbut.setEnabled(enable)
        self.ipinput.setEnabled(enable)
        self.portinput.setEnabled(enable)
        self.isconnected =  not enable
        if enable:
            self.icon = QIcon('dot-circle-red.png')
            self.statusbot.setIcon(self.icon)
            self.statusbot.setText("未连接")
        else:
            self.icon = QIcon('dot-circle.png')
            self.statusbot.setIcon(self.icon)
            self.statusbot.setText("已连接")

    def tcpKeepaliveCallback(self):
        print("TCP Keepalive started")
        while True:
            try:
                data = self.sck.recv(1024)
                if not data:
                    print("TCP Keepalive failed")
                    break
                print('recv:' + str(data.decode()))
            except Exception as e:
                print(e)
                break
        self.enableordisable(True)
        # self.callmsgBox('连接已断开')

    def tcpconnect(self):
        self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sck.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)
        self.sck.ioctl(socket.SIO_KEEPALIVE_VALS,(1, 5, 2))
        if self.ip != None and self.port != None and self.isconnected == False:
            try:
                self.sck.connect((self.ip, int(self.port)))
                self.enableordisable(False)
                print('连接成功')
                threading.Thread(target=self.tcpKeepaliveCallback).start()
            except Exception as e:
                print('tcp connect failed' + str(e))
                self.callmsgBox('连接失败：' + str(e))

    def tcpclose(self):
        if self.isconnected == True:
            self.sck.close()
            self.enableordisable(True)
            print("已断开")

    def tcpsend(self):
        print(self.file_path)
        if self.file_path != '' and self.fileflag == True:
            print('update file!')
            with open(self.file_path, 'rb') as f:
                self.cmd = f.read()
                print(self.cmd)
        if self.ip != None and self.sck != None and self.cmd != None and self.isconnected == True:
            if type(self.cmd) == bytes:
                try:
                    self.sck.send(self.cmd)
                    print(f"发送成功 + {self.cmd}")
                except Exception as e:
                    print('send failed ' + str(e))
                    self.enableordisable(True)
                    self.callmsgBox('发送失败：' + str(e))
            else:
                try:
                    self.sck.send(self.cmd.encode("utf-8"))
                    print(f"发送成功 + {self.cmd}")
                except Exception as e:
                    self.enableordisable(True)
                    print('send failed ' + str(e))
                    self.callmsgBox('发送失败：' + str(e))

    def setip(self, ip):
        print('ip: %s' % ip)
        self.ip = ip

    def setport(self, port):
        print('port: %s' % port)
        self.port = port

    def setcmd(self):
        self.fileflag = False
        # print('cmd: %s' % self.textbox.toPlainText())
        self.cmd = self.textbox.toPlainText()

    def fontTool(self):
        self.hboxFontTool.addWidget(self.filelist)
        self.hboxFontTool.addWidget(self.widgetright)
        self.checklocation.addItems(["Ram", "Flash"])
        self.checklocation.setStyleSheet("font:22px bold")
        
        self.vboxright.addWidget(self.checklocation)
        self.vboxright.addWidget(self.selectFolder)
        self.vboxright.addWidget(self.transformbut)

        self.widgetright.setMinimumSize(300, 800)
        self.filelist.setMinimumSize(300, 600)
        self.selectFolder.setMinimumSize(200,70)
        self.selectFolder.setMaximumSize(200,70)
        self.transformbut.setMinimumSize(200,70)
        self.transformbut.setMaximumSize(200,70)
        self.checklocation.setMaximumSize(200,45)
        
        self.filelist.setStyleSheet("QListWidget{font:18px bold}\
                                    QListWidget::item{height:40;}")
        self.hboxFontTool.setContentsMargins(10,10,0,10)
        self.vboxright.setContentsMargins(10,10,10,10)
        self.hboxFontTool.setSpacing(50)
        self.widgetright.setLayout(self.vboxright)
        self.widgetFirst.setLayout(self.hboxFontTool)
        for root,folders,files in os.walk(os.getcwd()):
            if root == os.getcwd():
                self.filelist.addItems(files)
        self.checklocation.currentIndexChanged.connect(self.updatelocation)
        self.selectFolder.clicked.connect(self.chooseFolder)
        self.transformbut.clicked.connect(self.starttransform)

    def tcpTool(self):
        self.textbox.setPlaceholderText("请输入指令")
        self.textbox.setMinimumSize(300,600)
        self.widgettcp.setMaximumSize(250,800)
        self.vboxtcp.setContentsMargins(10,10,10,10)
        self.hboxtcp.setContentsMargins(10,10,0,10)
        self.hboxtcp.setSpacing(50)

        self.hboxtcp.addWidget(self.textbox)
        self.hboxtcp.addWidget(self.widgettcp)
        self.hboxtcp.addSpacing(50)

        self.icon = QIcon('dot-circle-red.png')
        self.statusbot.setIcon(self.icon)
        self.statusbot.setStyleSheet("QPushButton{border:none;text-align:left;font:20px solid}")
        self.statusbot.setMaximumSize(200,70)
        self.vboxtcp.addWidget(self.statusbot)
        self.vboxtcp.addWidget(self.ipinput)
        self.vboxtcp.addWidget(self.portinput)
        self.vboxtcp.addWidget(self.choosefile)
        self.vboxtcp.addWidget(self.connectbut)
        self.vboxtcp.addWidget(self.sendbut)
        self.vboxtcp.addWidget(self.killbut)

        self.ipinput.setText(self.ip)
        self.portinput.setText(self.port)
        self.killbut.setMinimumSize(200,70)
        self.killbut.setMaximumSize(200,70)
        self.connectbut.setMaximumSize(200,70)
        self.connectbut.setMinimumSize(200,70)
        self.sendbut.setMinimumSize(200,70)
        self.sendbut.setMaximumSize(200,70)
        self.portinput.setMaximumSize(200,45)
        self.ipinput.setMaximumSize(200,45)
        self.choosefile.setMaximumSize(200,45)
        self.ipinput.setStyleSheet("font:18px")
        self.portinput.setStyleSheet("font:18px")
        self.textbox.setStyleSheet("font:18px")
        self.connectbut.setStyleSheet("font:18px")
        self.killbut.setStyleSheet("font:18px")
        self.sendbut.setStyleSheet("font:18px")

        self.textbox.textChanged.connect(self.setcmd)
        self.connectbut.clicked.connect(self.tcpconnect)
        self.killbut.clicked.connect(self.tcpclose)
        self.sendbut.clicked.connect(self.tcpsend)
        self.ipinput.textChanged.connect(self.setip)
        self.portinput.textChanged.connect(self.setport)
        self.choosefile.clicked.connect(self.chooseFile)

        self.widgettcp.setLayout(self.vboxtcp)
        self.widgetSecond.setLayout(self.hboxtcp)

    def moyuCallback(self):
        pagui.alert("摸鱼线程运行完成", 'app提示', 'OK')
        self.moyubut.setEnabled(True)

    def startMoyuThread(self):
        threading.Thread( target = moyuFunction, name="moyuThread", args=(self.moyuCallback, )).start()
        pagui.alert("摸鱼线程已后台运行", 'app提示', 'OK')
        self.moyubut.setEnabled(False)

    def notifyWin(self):
        self.vboxNotifyLeft.addWidget(self.wetlabel)
        self.vboxNotifyLeft.addWidget(self.templabel)
        self.vboxNotifyLeft.addWidget(self.moyubut)
        self.moyubut.setMinimumSize(600,60)
        self.moyubut.setMaximumSize(600,60)
        self.vboxNotifyLeft.addSpacing(500)
        self.widgetNotifyLeft.setLayout(self.vboxNotifyLeft)
        
        self.hboxNotify.addWidget(self.widgetNotifyLeft)
        self.widgetNotify.setLayout(self.hboxNotify)
        self.widgetNotifyLeft.setStyleSheet("font:20px solid")

        self.moyubut.clicked.connect(self.startMoyuThread)

    def msgBoxinit(self):
        self.msgBox.addButton(QMessageBox.Ok)
        self.msgBox.setWindowIcon(QIcon("./output.ico"))
        self.msgBox.setIcon(QMessageBox.Information)
        self.msgBox.setWindowTitle("提示消息")

    def callmsgBox(self, msg):
        self.msgBox.setText(msg)       
        ret = self.msgBox.exec_()
        if ret == QMessageBox.Ok:
            print("user push ok")
       

    def __init__(self):
        print("小程序启动")
        self.file_path = ''
        self.fileflag = False
        self.ip = '199.9.10.97'
        self.port = '9100'
        self.sck = None
        self.cmd = None
        self.isconnected = False
        self.location = 'R:'
        self.app = QApplication(sys.argv)
        self.win = QMainWindow()
        self.win.setWindowIcon(QIcon("./output.ico"))
        self.desktopwidth = QDesktopWidget().screenGeometry().width()
        print("Desktop width: " + str(self.desktopwidth))
        self.win.setGeometry(int(self.desktopwidth/2), 200, 800, 800)
        self.win.setWindowTitle("myApp" + self.version)
        #初始化小组件
        self.msgBox = QMessageBox()
        self.widgetAll = QWidget()
        self.widgetFirst = QWidget()
        self.widgetSecond = QWidget()
        self.widgetNotify = QWidget()
        self.widgetNavi = QWidget()
        self.vboxNavi = QVBoxLayout()
        self.stack = QStackedWidget() 
        self.but = [] 
        self.filelist = QListWidget()
        self.widgetright = QWidget()
        self.vboxright = QVBoxLayout()
        self.hboxFontTool = QHBoxLayout()
        self.selectFolder = QPushButton("选择文件夹")
        self.transformbut = QPushButton("开始转换")
        self.checklocation = QComboBox()
        self.textbox = QTextEdit()      #tcp界面
        self.hboxtcp = QHBoxLayout()
        self.vboxtcp = QVBoxLayout()
        self.widgettcp = QWidget()
        self.ipinput = QLineEdit()
        self.portinput = QLineEdit()
        self.sendbut = QPushButton("发送")
        self.connectbut = QPushButton("连接")
        self.killbut = QPushButton("断开")
        self.choosefile = QPushButton("选择文件")
        self.statusbot = QPushButton("未连接")
        self.hboxNotify = QHBoxLayout()         #监测界面
        self.widgetNotifyLeft = QWidget()
        self.widgetNotifyRight = QWidget()
        self.hboxNotifyRight = QVBoxLayout()
        self.vboxNotifyLeft = QVBoxLayout()
        self.hboxwet = QHBoxLayout()
        self.hboxtemp = QHBoxLayout()
        self.wetlabel = QLabel("当前湿度：")
        self.templabel = QLabel("当前温度：")
        self.moyubut = QPushButton("摸鱼开始")
        self.serverip = QLineEdit("199.9.10.97")
        self.serverport = QLineEdit()


        #初始化消息通知界面
        self.msgBoxinit()

        #定义总界面布局
        self.widgetNavi.setMinimumSize(200,800)
        self.stack.setMinimumSize(600,800)
        hboxAll = QHBoxLayout()
        hboxAll.addWidget(self.widgetNavi)
        hboxAll.addWidget(self.stack)
        hboxAll.setContentsMargins(0, 0, 0, 0)
        hboxAll.setSpacing(0)
        
        self.stack.addWidget(self.widgetSecond)
        self.stack.addWidget(self.widgetFirst)
        self.stack.addWidget(self.widgetNotify)

        #导航按钮布局
        for i in range(3):
            self.but.append(QPushButton())
            self.but[i].setMinimumSize(180,70)
            self.but[i].setStyleSheet("QPushButton{\
                            border: 2px solid black;\
                            border-radius: 10px;\
                            font:20px bold;}\
                            QPushButton::hover{background-color:rgba(95, 95, 95, 0.95);}\
                            QPushButton::checked{background-color:rgba(95, 95, 95, 0.95);}")
            self.but[i].setCheckable(True)
        self.but[0].setText("TCP连接工具")
        self.but[1].setText("字体转换工具")
        self.but[2].setText("监测面板")
        self.but[0].setChecked(True)
        self.vboxNavi.addWidget(self.but[0])
        self.vboxNavi.addWidget(self.but[1])
        self.vboxNavi.addWidget(self.but[2])
        self.vboxNavi.addSpacing(590)
        self.vboxNavi.setContentsMargins(5, 5, 10, 5)
        self.vboxNavi.setSpacing(2)
        self.widgetNavi.setLayout(self.vboxNavi)
        self.but[0].clicked.connect(self.transto1)
        self.but[1].clicked.connect(self.transto2)
        self.but[2].clicked.connect(self.transto3)
        
        #TCP连接工具 
        self.tcpTool()

        #字体转换工具界面
        self.fontTool()
        
        #监测窗口界面
        self.notifyWin()

        # 敬请期待
        label2 = QLabel()
        # label2.setText("敬请期待")
        
        #debug图层
        self.widgetNavi.setStyleSheet("background-color:#363636;border-right:5px solid black;")
        # self.widgetFirst.setStyleSheet("background-color:#363636;")
        # self.widgetSecond.setStyleSheet("background-color:#363636;")
        # self.widgetNotify.setStyleSheet("background-color:#363636;")
        self.widgetAll.setStyleSheet("color:#ffffff;background-color:#363636;")
        self.widgetAll.setLayout(hboxAll)
        self.win.setCentralWidget(self.widgetAll)
        self.win.show()
        sys.exit(self.app.exec_())

# def CVCNNtest():
#     import os
#     os.environ["KERAS_BACKEND"] = "tensorflow"  # Or "jax" or "torch"!

#     import tensorflow as tf
#     import keras_cv
#     import tensorflow_datasets as tfds
#     import keras

#     # Create a preprocessing pipeline with augmentations
#     BATCH_SIZE = 16
#     NUM_CLASSES = 3
#     augmenter = keras_cv.layers.Augmenter(
#         [
#             keras_cv.layers.RandomFlip(),
#             keras_cv.layers.RandAugment(value_range=(0, 255)),
#             keras_cv.layers.CutMix(),
#         ],
#     )

#     def preprocess_data(images, labels, augment=False):
#         labels = tf.one_hot(labels, NUM_CLASSES)
#         inputs = {"images": images, "labels": labels}
#         outputs = inputs
#         if augment:
#             outputs = augmenter(outputs)
#         return outputs['images'], outputs['labels']

#     train_dataset, test_dataset = tfds.load(
#         'rock_paper_scissors',
#         as_supervised=True,
#         split=['train', 'test'],
#     )
#     train_dataset = train_dataset.batch(BATCH_SIZE).map(
#         lambda x, y: preprocess_data(x, y, augment=True),
#             num_parallel_calls=tf.data.AUTOTUNE).prefetch(
#                 tf.data.AUTOTUNE)
#     test_dataset = test_dataset.batch(BATCH_SIZE).map(
#         preprocess_data, num_parallel_calls=tf.data.AUTOTUNE).prefetch(
#             tf.data.AUTOTUNE)

#     # Create a model using a pretrained backbone
#     backbone = keras_cv.models.EfficientNetV2Backbone.from_preset(
#         "efficientnetv2_b0_imagenet"
#     )
#     model = keras_cv.models.ImageClassifier(
#         backbone=backbone,
#         num_classes=NUM_CLASSES,
#         activation="softmax",
#     )
#     model.compile(
#         loss='categorical_crossentropy',
#         optimizer=keras.optimizers.Adam(learning_rate=1e-5),
#         metrics=['accuracy']
#     )

#     # Train your model
#     model.fit(
#         train_dataset,
#         validation_data=test_dataset,
#         epochs=8,
#     )

if __name__ == '__main__':
    current_path = os.getcwd()
    print("当前位置：" + current_path)
    # dataAnalysis()
    # CVCNNtest()
    # getRealImage('./images/11.png')
    #运行小程序
    app = myApp()

    
